/* This file contains functions which are used to read and write config files */
#include "global.h"
#include "configfile.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <assert.h>
#include <errno.h>

#define ENTRY_LENGTH 64
#define CONFIG_FILE "/etc/lknnu.conf"

Config_Info *config_info;
char	*l_name,
	*l_password;
	
char tmp_value[ENTRY_LENGTH];

static char *get_value(FILE *stream, const char *entry);


//read the config file (/etc/lknnu.conf),and load all sections.
int
load_config(void)
{
	FILE *fp = NULL;
	
	if ( (fp = fopen(CONFIG_FILE, "rt")) == NULL){
		fprintf(stderr, "open configfile err: %s", strerror(errno));
		return -1;
	}
	
	config_info = (Config_Info *)malloc(sizeof(Config_Info));
	get_value((FILE *) fp, "AutoRetry");
	config_info->auto_retry = atoi(tmp_value);

	get_value((FILE *) fp, "MaxServerResponseTime");
	config_info->response_time_out = atoi(tmp_value);

	get_value((FILE *) fp, "RetryNumber");
	config_info->retry_times = atoi(tmp_value);

	get_value((FILE *) fp, "WaitTime");
	config_info->refresh_time_out = atoi(tmp_value);

	get_value((FILE *) fp, "Device");
	config_info->interface = (char *)malloc(sizeof(tmp_value) + 1);
	strcpy(config_info->interface, tmp_value);

	get_value((FILE *) fp, "AccountName");

	//printf("%s\n",tmp_value);
        l_name = (char *) malloc (13 * sizeof(char));
	strncpy(l_name, tmp_value, 8);
	l_name[8] = '\0';
	strncat(l_name, "@edu",4 * sizeof(char)); //There is no need for us to judge if it is internet or not.
        l_name[12] = '\0';

	get_value((FILE *) fp, "AccountPasswd");
	l_password = (char *) malloc (strlen(tmp_value) + 1);
	strcpy(l_password, tmp_value);
	
	fclose(fp);
	return 1;
}

void 
free_config(void)
{
	free(config_info->interface);
	free(config_info);
	free(l_name);
	free(l_password);
}


char *
get_value(FILE *stream, const char *entry_name)
{
	assert(stream != NULL);
	
	char *tmp = NULL;
	int len = strlen(entry_name);
	
	tmp = (char *)calloc(1, ENTRY_LENGTH + 1);
	
	while ( fgets( tmp, ENTRY_LENGTH, stream) != NULL){
		if(tmp[strlen(tmp) - 1] == '\n')
			tmp[strlen(tmp) - 1] = '\0';
		
		if ( isalpha(*tmp))
			if ( !strncmp(tmp, entry_name, len)){
				strcpy(tmp_value, tmp + len + 1);
				free(tmp);
				return tmp_value;
			}
	}
	return NULL;
}
